import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import { getToken, removeToken } from '@/utils/cookie-utils'

import RouterConfig from './config.js' // 导入配置项
import { whiteList, constantRouterMap, asyncRouterMap, errRouterMap } from './router.js' // 路由列表(白名单，无需权限路由,异步路由[API路由],错误页面路由)


// 加载权限原子控制组件
import Privilege from './privilege.js'
// 页面中使用 v-auth 标签控制权限，auth 名称可以自定义
// Vue.directive('auth', Privilege)
Vue.directive(RouterConfig.authDirective || 'auth', Privilege)

Vue.use(Router)

// =================也可以把router.js路由地址项写在此次=================

// 注册路由
export const router = new Router({
  // mode: 'history', // 去掉url中的#
  mode: '#', // 去掉url中的#
  routes: constantRouterMap
})

// 掩藏白屏加载动画
function hiddenLoader () {
  try {
    var loader = document.getElementById('loader-wrapper')
    if (loader) {
      // loader.remove()
      loader.parentNode.removeChild(loader)
    }
  } catch (error) {
    // console.log(error)
  }
}


/**
 * 根据权限匹配路由
 * @param {array} permission 权限列表（菜单列表）
 * @param {array} asyncRouter 异步路由对象
 */
 function routerMatch (permission, asyncRouter) {
  // console.log('对比原始数据', permission, asyncRouter)
  return new Promise((resolve) => {
    const routers = []
    // 创建路由
    function createRouter (permission) {
      // 根据路径匹配到的router对象添加到routers中即可
      permission.forEach((item) => {
        if (item.children && item.children.length) {
          createRouter(item.children)
        }
        // let path = item[RouterConfig.apiPathField] // 个性化接口字段配置
        let path = item[RouterConfig.apiPermissionField] // 个性化接口字段配置[权限标识]
        let useAlias = RouterConfig.useAlias || false // 是否使用别名映射
        let apiAliasConfig = RouterConfig.apiAlias || {} // 配置项中的映射
        let permissIsStr = typeof (item[RouterConfig.apiPermissionField]) === 'string' // 接口返回的权限字段是否为字符串
        item[RouterConfig.apiPermissionField] = permissIsStr ? [item[RouterConfig.apiPermissionField]] : item[RouterConfig.apiPermissionField]
        // 循环异步路由，将符合权限列表的路由加入到routers中
        asyncRouter.find((s) => {
          // 如果vue路由表中 path字段为空或者设置了 children 子路由，则遍历子路由
          if (s.children && s.children.length > 0) {
          // if (s[RouterConfig.routerConfigPathField] === '') {
            s.children.find((y) => {
              if (useAlias) {
                // if (y.path === path) {
                if (apiAliasConfig[y[RouterConfig.routerConfigPathField]] === path) {
                  y.meta.permission = item[RouterConfig.apiPermissionField]
                  // y.meta.permission = item.permission
                  routers.push(s)
                }
              } else {
                if (y[RouterConfig.routerConfigPathField] === path) {
                  y.meta.permission = item[RouterConfig.apiPermissionField]
                  // y.meta.permission = item.permission
                  routers.push(s)
                }
              }
            })
          }
          if (useAlias) {
            if (apiAliasConfig[s[RouterConfig.routerConfigPathField]] === path) {
              s.meta.permission = item[RouterConfig.apiPermissionField]
              // y.meta.permission = item.permission
              routers.push(s)
            }
          } else {
            if (s[RouterConfig.routerConfigPathField] === path) {
              s.meta.permission = item[RouterConfig.apiPermissionField]
              // y.meta.permission = item.permission
              routers.push(s)
            }
          }
        })
      })
    }
    createRouter(permission)
    resolve([routers])
  })
}

/**
 * 判断是否加载权限路由
 * @param {array} permission 权限列表（菜单列表）
 * @param {array} asyncRouter 异步路由对象
 */
function loadAuthRouter(routerObj,toRouter){
  // console.log('routerObj',routerObj,asyncRouterMap,toRouter)
  if(store.getters.isLogin){
    if(window.name == "refresh"){
      store.commit('setLoadAuthRouter',true)
      console.log('loadAuthRouter 刷新========',true)
      return true;
    }
    if(store.getters.hasLoadAuthRouter){
      console.log('loadAuthRouter',false)
      return false
    }
    store.commit('setLoadAuthRouter',true)
    console.log('loadAuthRouter',true)
    return true;
  }else{
    console.log('loadAuthRouter',false)
    return false
  }
}

function delRouter(router){
    const createRouter = () => new Router({
      // mode: 'history', // 去掉url中的#
      mode: '#', // 去掉url中的#
      routes: constantRouterMap
    })

    // 用初始化的matcher替换当前router的matcher
    router.matcher = createRouter.matcher

}

// 导航钩子
router.beforeEach((to, form, next) => {
  let loginRoute = RouterConfig.loginRouteName || '/login'
  let homeRoute = RouterConfig.homeRouteName || '/home'
  let errRoute = RouterConfig.errRouteName || '/err'

  // 设置标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  next()
  if (getToken()) {
  // if (store.getters.isLogin) {
    console.log('to',to)
    if (to.path === '/') {
      next({ path: '/home' })
    }else{
     
          console.log('home',to,store.getters.not_init)
          // next()
          // next(to.path)
          // router.push({ path: '/HomeMain', });;
    
          console.log('router router',router)
    
          // if(store.getters.not_init){
          if(loadAuthRouter(router,to)){
            router.addRoutes(asyncRouterMap)
            // 动态添加 错误页面路由
            router.addRoutes(errRouterMap)
            console.log('进入2')
            hiddenLoader() // 删除加载动画
            next(to.path)
          }else{
            if (to.matched.length) {
              // next(to.path)
              // router.replace(to.path)
              next()
            } else {
              // if (!store.getters.isLogin) {
                // router.replace(loginRoute)
              // }else{
                  next({ path: '/err' })
              //     next({ path: errRoute })
              //     // router.replace('/login')
              // }
              
            }
          }
      
    }
  } else {
    console.log('else')
    hiddenLoader() // 删除加载动画
    if (whiteList.indexOf(to.path) >= 0) {
      console.log('白名单')
      next()
    } else {
      // delRouter(router)
      console.log('去登录',loginRoute)
      // next({ path: loginRoute })
      // next(loginRoute)
      router.replace(loginRoute)
    }
  }
})

export default router